package org.foj.presenter {
import mx.collections.ArrayCollection;
import mx.controls.Alert;
import mx.managers.CursorManager;
import mx.rpc.AsyncResponder;
import mx.rpc.AsyncToken;
import mx.rpc.events.FaultEvent;
import mx.rpc.events.ResultEvent;

import org.foj.dto.Issue;
import org.foj.event.EventDispatcherFactory;
import org.foj.event.UIEvent;
import org.foj.model.IssueModel;
import org.foj.model.GraphModel;
import org.foj.view.GraphView;

public class GraphPresenter {

  private var _view:GraphView;
  private var _issueModel:IssueModel;
  private var helper:GraphModel;

  private var _groupByValues:ArrayCollection =
      new mx.collections.ArrayCollection([
        {
          label: "Project",
          data: "project"
        },
        {
          label: "Status",
          data: "status"
        },
        {
          label: "Type",
          data: "type"
        },
        {
          label: "Severity",
          data: "severity"
        }
      ]);

  public function GraphPresenter(view:GraphView) {
    this._issueModel = new IssueModel();
    this._view = view;

    helper = new org.foj.model.GraphModel();

    EventDispatcherFactory.getEventDispatcher()
        .addEventListener(UIEvent.REFRESH_GRAPHS, refreshGraphs);

    _view.groupByComboBox.dataProvider = _groupByValues;
  }

  private function refreshGraphs(event:UIEvent = null):void {
    CursorManager.setBusyCursor();
    _issueModel.getIssues(new AsyncResponder(getIssuesResult,
        handleError));
  }

  private function getIssuesResult(event:ResultEvent,
                                   token:AsyncToken = null):void {
    CursorManager.removeBusyCursor();
    var issues:ArrayCollection = new ArrayCollection();

    for each(var item:Object in event.result) {
      var issue:Issue = new Issue(item);
      issues.addItem(issue);
    }

    _view.issuesPieChart.dataProvider =
    helper.groupCollectionBy(issues,
        _view.groupByComboBox.selectedItem.data);
  }

  private function handleError(event:FaultEvent,
                               token:AsyncToken = null):void {
    CursorManager.removeBusyCursor();
    Alert.show(event.message.toString());
  }

}
}